"""
功能实现：实现邮件配置，和对外提供发送邮件的方法
导包
配置邮箱属性
组装邮件内容，和标题和附件
连接登录并发送
"""
import smtplib,time,os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

class sendexcel():
    def __init__(self):
        # 发件人
        self.sender='825622958@qq.com'
        # 收件人
        self.receiver='825622958@qq.com'
        # 定义邮件时间格式
        t=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        # 定义名称
        self.subject='自动化测试结果'+t
        # 指定发送邮件类型
        self.smtpserver='smtp.qq.com'
        # 发件人账户
        self.username='825622958@qq.com'
        # 发件人密码
        self.password='dfgtfujqrceqbbgd'

    def __config(self, file):

        # 第二步：准备附件，增加附件，组装邮件内容和标题
        # 读取html文件内容
        with open(file, 'rb') as f:
            mail_body = f.read()
            # 组装邮件内容和标题
            self.msg = MIMEMultipart()
            # 添加附件内容
            att = MIMEText(mail_body, 'plain', 'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att["Content-Disposition"] = 'attachment; filename=report.html'
            self.msg.attach(att)
            # 添加邮件的文本内容
            content = '自动化测试报告详情，请查收附件'
            self.msg.attach(MIMEText(content, 'plain', 'utf-8'))
            self.msg['Subject'] = Header(self.subject, 'utf-8')
            self.msg['From'] = self.sender
            self.msg['To'] = self.receiver

    def send(self,file):
        self.__config(file)
        try:
            smtp=smtplib.SMTP()
            smtp.connect(self.smtpserver)
            smtp.login(self.username,self.password)
            smtp.sendmail(self.sender,self.receiver,self.msg.as_string())
        except Exception as msg:
            print("邮件发送失败 %s" % msg)
        else:
            print('邮件发送成功')
        finally:
            smtp.quit()

if __name__ == '__main__':
    ce=sendexcel()
    cur_dir = os.path.dirname(os.path.dirname(__file__)) + '/testreport/2022-07-17 21-22-38result.html'
    ce.send(cur_dir)